from rest_framework.pagination import LimitOffsetPagination, _positive_int

from gesture_demo_server.common.result import BaseResponse


class CustomLimitOffsetPagination(LimitOffsetPagination):
    limit = None

    def get_limit(self, request):
        if self.limit_query_param:
            try:
                value = request.query_params[self.limit_query_param]
                if int(value) == -1:
                    return int(value)
                else:
                    return _positive_int(
                        value,
                        strict=True,
                        cutoff=self.max_limit
                    )
            except (KeyError, ValueError):
                pass
        return self.default_limit

    def paginate_queryset(self, queryset, request, view=None):
        self.limit = self.get_limit(request)
        if self.limit == -1:
            return list(queryset)
        return super(CustomLimitOffsetPagination, self).paginate_queryset(queryset, request, view=None)

    def get_paginated_response(self, data):
        return BaseResponse(data={'count': self.count, 'results': data})
